package qeug.shsh.opplugin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huawei.shade.org.apache.commons.logging.Log;
import com.huawei.shade.org.apache.commons.logging.LogFactory;
import com.sap.db.util.Base64Utils;
import kd.bos.context.RequestContext;
import kd.bos.openapi.common.result.OpenApiResult;
import kd.bos.openapi.common.util.OpenApiSdkUtil;
import kd.bos.servicehelper.DispatchServiceHelper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.MediaType;
import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.form.FormMetadataCache;
import kd.bos.form.ShowType;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import qeug.shsh.bpm.domain.*;
import qeug.shsh.bpm.service.impl.BPMServiceImpl;
import qeug.shsh.helper.FacadeHelper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;


///废弃插件，未使用
public class ShowApprovalsBillPlugin extends AbstractFormPlugin {
    private final static Log logger = LogFactory.getLog(ShowApprovalsBillPlugin.class);//日志

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("tbmain");//监听按钮
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        if (evt.getItemKey().equalsIgnoreCase("qeug_approval_record")) {
            String name = this.getModel().getDataEntityType().getName();
            String billNo = this.getModel().getDataEntity(true).getString("billno");//单据编码
            QFilter[] qFilter = new QFilter[]{
                    new QFilter("billno", QCP.equals, billNo)};
            DynamicObject inventory = null;
            boolean a = name.equals("er_publicreimbursebill") || name.equals("er_dailyloanbill") || name.equals("qeug_fundplan") || name.equals("qeug_fundadjust");
            if (a) {
                //付款申请，借款单，资金计划，资金计划调整
                inventory = BusinessDataServiceHelper.loadSingle("qeug_auditlogv2", "billno", qFilter);//BPM审批记录（新）
            } else {
                //费用报销单，差旅报销单，预算调整单
                inventory = BusinessDataServiceHelper.loadSingle("qeug_auditlog", "billno", qFilter);//BPM审批记录（旧）
            }
            if (inventory != null) {
                String pkId = inventory.getString("id");
                BillShowParameter showParameter = new BillShowParameter();
                if (a) {
                    //付款申请，借款单，资金计划，资金计划调整
                    showParameter.setFormId("qeug_auditlogv2");
                } else {
                    //费用报销单，差旅报销单，预算调整单
                    showParameter.setFormId("qeug_auditlog");
                }
                showParameter.getOpenStyle().setShowType(ShowType.Modal); //打开方式
                showParameter.setPkId(pkId);
                if (showParameter.getFormConfig() == null) {
                    if (a) {
                        showParameter.setFormConfig(FormMetadataCache.getFormConfig("qeug_auditlogv2"));
                    } else {
                        showParameter.setFormConfig(FormMetadataCache.getFormConfig("qeug_auditlog"));
                    }
                }
                showParameter.getFormConfig().setHeight(new LocaleString("650"));
                showParameter.getFormConfig().setWidth(new LocaleString("1200"));
                getView().showForm(showParameter);
            } else {
                this.getView().showErrorNotification(billNo + "无审批记录！");
            }
        } else if (evt.getItemKey().equalsIgnoreCase("qeug_baritemap")) {
//            String invoicecode = "";
//            String invoiceNo = "";
//            DynamicObject dataEntity = this.getModel().getDataEntity(true);
//            //发票分录
//            DynamicObjectCollection invoiceCollection = dataEntity.getDynamicObjectCollection("invoiceentry");
//            for (int i = 0; i < invoiceCollection.size(); i++) {
//                DynamicObject invoiceEntry = invoiceCollection.get(i);
//                invoicecode = invoiceEntry.getString("serialno");
//                InvoiceEntrys invoice1 = new InvoiceEntrys();
//                System.out.println();
//            }
//            List<String> objects = new ArrayList<>();
//            objects.add(invoicecode);//发票流水号
//            Map<String, Object> result = DispatchServiceHelper.invokeBizService("imc", "rim", "FpzsService", "query", objects);
//            Object errcode = result.get("errcode");//请求状态码，为0000表示成功
//            Object data = result.get("data");//请求返回数据
//            JSONArray jsonArray = JSONArray.parseArray(data.toString());
//            for (int i = 0; i < jsonArray.size(); i++) {
//                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                invoiceNo = jsonObject.getString("downloadUrl");
//            }
//            String token = null;
//            String downloadUrl = null;
//            try {
//                token = FacadeHelper.getToken();
//                downloadUrl = FacadeHelper.getDownloadUrl("http://10.10.102.30:30088/ierp", invoiceNo, token);//1e66deefe9004000为downloadUrl源文件URL
//                int index = downloadUrl.indexOf('&');
//                String desiredUrl = (index != -1) ? downloadUrl.substring(0, index) : downloadUrl;
//                System.out.println();
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println();
//            Map<String, Object> bodyMap = bodyJson.toJavaObject(HashMap.class);
//            Map body1 = new HashMap<String, String>();
//            body1.put("interfaceCode"," INVOICE.QUERY");
//            OpenApiResult saveResult = (OpenApiResult) OpenApiSdkUtil.invokeOpenApi("/kapi/app/sim/openApi", bodyMap, null);

            // 发票推送报文
//            HashMap<String, Object> log = new HashMap<>();
//            log.put("mainstring", "发票推送测试开始---------");
//            logger.info("发票推送测试开始---------");
//
//            // 直接构造 Map 类型参数
//            Map<String, Object> bodyMap = new HashMap<>();
//            bodyMap.put("interfaceCode", "INVOICE.QUERY");
//            bodyMap.put("messageType", "invoiceQuery");
//            bodyMap.put("businessSystemCode", "");
//
//            // 嵌套 data 字段
//            Map<String, Object> data = new HashMap<>();
//            data.put("pageNo", 1);
//            data.put("pageSize", 10);
//            bodyMap.put("data", data);
//            OpenApiResult saveResult = (OpenApiResult) OpenApiSdkUtil.invokeOpenApi("/kapi/app/sim/openApi", bodyMap, null);


//            Invoice invoice = new Invoice();//发票报文
//            invoice.setMessageType(MessageType.INVOICE_QUERY);//请求类型:invoiceQuery
//            invoice.setMessageId("131002260201");//请求id
//            Data data = new Data();//请求内容
//            data.setPageNo(1);//页码;页码从1开始
//            data.setPageSize(1);//每页数量，最大500
//            data.setInvoiceDateStart("");//开票日期起:yyyy-MM-dd
//            data.setInvoiceDateEnd("");//开票日期止:yyyy-MM-dd
//            data.setInvoiceType("");//发票类型
//            data.setInvoiceStatus(InvoiceStatus.THE_0);//增值税发票状态
//            data.setInvoiceCode("");//发票代码
//            data.setInvoiceNo("");//发票号
//            invoice.setData(data);
//            String json1 = JSONObject.toJSONString(invoice);
//            log.put("responsebody", "1" + json1);
//            FacadeHelper.apiLog(log);
//            RequestBody body = RequestBody.create(mediaType, json1);

//            OkHttpClient client = new OkHttpClient();
//            Request request = null;
//            try {
//
//                System.out.println();
////                String urlWithToken = "https://10.10.102.30/jdpjykjyxgs/kapi/app/sim/openApi?access_token=" + token;
//                String urlWithToken = "https://open-ultimate.piaozone.com/api-145421056?access_token=" + token;
//                request = new Request.Builder()
//                        .url(urlWithToken)
//                        .method("POST", body)
//                        .addHeader("Content-Type", "application/json")
//                        .build();
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//            try {
//                Response response = client.newCall(request).execute();
//                if (response.isSuccessful()) {
//                    // 获取原始响应内容
//                    String responseBody = Objects.requireNonNull(response.body()).string();
//                    log.put("responsebody", "2" + responseBody);
//                    FacadeHelper.apiLog(log);
//                    logger.info("解密后响应报文：\n" + responseBody);
//
//                    // 如果响应是base64编码（根据接口文档判断）
//                    // String decodedResponse = new String(Base64Utils.decodeFromString(responseBody), StandardCharsets.UTF_8);
//
//                    // 如果直接返回json
//                    String formattedJson = JSONObject.parseObject(responseBody).toJSONString();
//                    logger.info("解密后响应报文2：\n" + formattedJson);
//                } else {
//                    logger.info("请求失败，状态码：" + response.code());
//                }
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }
            //发票推送报文
//            HashMap<String, Object> log = new HashMap<>();
//            log.put("mainstring", "发票推送测试开始---------");
//            logger.info("发票推送测试开始---------");
//            MediaType mediaType = MediaType.parse("application/json");
//            JSONObject bodyJson = new JSONObject();
//            bodyJson.put("interfaceCode", " INVOICE.QUERY");
//            bodyJson.put("messageType", "invoiceQuery");
//            bodyJson.put("businessSystemCode", "");
//            JSONObject data = new JSONObject();
//            data.put("pageNo", 1); // 页码，例如 1
//            data.put("pageSize", 10); // 每页数量，例如 10
//            bodyJson.put("data", data);
//            RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
        }
    }

    public static String getAccess_Token() throws IOException {
        String loginIP = RequestContext.get().getLoginIP();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\n    \"appId\": \"FPY001\",\n    \"appSecret\": \"FPY001fpy@2023fpy\",\n    \"accountId\": \"1742050739649250304\",\n    \"tenantid\": \"1\",\n    \"language\": \"en\"\n}");
        Request request = new Request.Builder()
                .url("https://cosmic-sandbox.piaozone.com/jdpjykjyxgs/api/getAppToken.do")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        String app_token = jsonObject.getJSONObject("data").getString("app_token");
        JSONObject bodyjson = new JSONObject();
        bodyjson.put("user", "15815530006");
        bodyjson.put("apptoken", app_token);
        bodyjson.put("tenantid", "");
        bodyjson.put("accountId", "1742050739649250304");
        bodyjson.put("usertype", "Mobile");
        RequestBody body1 = RequestBody.create(mediaType, bodyjson.toJSONString());
        Request request1 = new Request.Builder()
                .url("https://cosmic-sandbox.piaozone.com/jdpjykjyxgs/api/login.do")
                .method("POST", body1)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response1 = client.newCall(request1).execute();
        JSONObject jsonObject1 = JSONObject.parseObject(response1.body().string());
        return jsonObject1.getJSONObject("data").getString("access_token");
    }
}
